package com.jeesite.modules.exam.score.service;

import cn.hutool.core.stream.CollectorUtil;
import com.jeesite.common.entity.Page;
import com.jeesite.common.idgen.IdGen;
import com.jeesite.common.service.CrudService;
import com.jeesite.common.service.ServiceException;
import com.jeesite.modules.backlog.service.DcSupBacklogService;
import com.jeesite.modules.common.service.SysOfficeUnitService;
import com.jeesite.modules.exam.assessment.entity.DcSupExamInfo;
import com.jeesite.modules.exam.assessment.service.DcSupExamInfoService;
import com.jeesite.modules.exam.quota.dao.DcSupExamQuotaAddDao;
import com.jeesite.modules.exam.quota.entity.DcSupExamQuota;
import com.jeesite.modules.exam.quota.entity.DcSupExamQuotaAdd;
import com.jeesite.modules.exam.quota.entity.DcSupExamSumQuotaInfo;
import com.jeesite.modules.exam.quota.service.DcSupExamQuotaAddService;
import com.jeesite.modules.exam.quota.service.DcSupExamQuotaService;
import com.jeesite.modules.exam.quota.service.DcSupExamSumQuotaInfoService;
import com.jeesite.modules.exam.score.dao.DcSupExamScoreDao;
import com.jeesite.modules.exam.score.dao.DcSupExamSumScoreDao;
import com.jeesite.modules.exam.score.entity.DcSupExamScore;
import com.jeesite.modules.exam.score.entity.DcSupExamSumScore;
import com.jeesite.modules.exam.score.vo.DcSupExamQuotaOrgVo;
import com.jeesite.modules.exam.score.vo.DcSupExamVo;
import com.jeesite.modules.file.utils.FileUploadUtils;
import com.jeesite.modules.sys.entity.Office;
import com.jeesite.modules.sys.utils.EmpUtils;
import com.jeesite.modules.sys.utils.UserUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 考核任务评分汇总表Service
 * @author xhc
 * @version 2022-05-28
 */
@Service
@Transactional(readOnly=false)
@RequiredArgsConstructor
public class DcSupExamSumScoreService extends CrudService<DcSupExamSumScoreDao, DcSupExamSumScore> {

	private final DcSupExamScoreService dcSupExamScoreService;

	private final DcSupExamQuotaAddDao dcSupExamQuotaAddDao;

	private final DcSupExamOrgScoreService dcSupExamOrgScoreService;

	private final DcSupExamScoreDao dcSupExamScoreDao;

	private final SysOfficeUnitService sysOfficeUnitService;

	private final DcSupExamQuotaAddService dcSupExamQuotaAddService;

	private final DcSupExamInfoService dcSupExamInfoService;

	private final DcSupExamQuotaService dcSupExamQuotaService;

	private final DcSupExamSumQuotaInfoService dcSupExamSumQuotaInfoService;

	private final DcSupBacklogService dcSupBacklogService;

	/**
	 * 获取单条数据
	 *
	 * @param dcSupExamSumScore
	 * @return
	 */
	@Override
	public DcSupExamSumScore get(DcSupExamSumScore dcSupExamSumScore) {
		return super.get(dcSupExamSumScore);
	}

	/**
	 * 查询分页数据
	 *
	 * @param dcSupExamSumScore      查询条件
	 * @param dcSupExamSumScore.page 分页对象
	 * @return
	 */
	@Override
	public Page<DcSupExamSumScore> findPage(DcSupExamSumScore dcSupExamSumScore) {
		return super.findPage(dcSupExamSumScore);
	}

	/**
	 * 查询列表数据
	 *
	 * @param dcSupExamSumScore
	 * @return
	 */
	@Override
	public List<DcSupExamSumScore> findList(DcSupExamSumScore dcSupExamSumScore) {
		return super.findList(dcSupExamSumScore);
	}

	/**
	 * 保存数据（插入或更新）
	 *
	 * @param dcSupExamSumScore
	 */
	@Override
	@Transactional(readOnly = false)
	public void save(DcSupExamSumScore dcSupExamSumScore) {
		super.save(dcSupExamSumScore);
		// 保存上传图片
		FileUploadUtils.saveFileUpload(dcSupExamSumScore, dcSupExamSumScore.getId(), "dcSupExamSumScore_image");
		// 保存上传附件
		FileUploadUtils.saveFileUpload(dcSupExamSumScore, dcSupExamSumScore.getId(), "dcSupExamSumScore_file");
	}

	/**
	 * 更新状态
	 *
	 * @param dcSupExamSumScore
	 */
	@Override
	@Transactional(readOnly = false)
	public void updateStatus(DcSupExamSumScore dcSupExamSumScore) {
		super.updateStatus(dcSupExamSumScore);
	}

	/**
	 * 删除数据
	 *
	 * @param dcSupExamSumScore
	 */
	@Override
	@Transactional(readOnly = false)
	public void delete(DcSupExamSumScore dcSupExamSumScore) {
		super.delete(dcSupExamSumScore);
	}


	/**
	 * 获取评分汇总单位
	 *
	 * @param
	 * @param o
	 * @return
	 */
	public List<DcSupExamQuotaOrgVo> findSumAssessmentUnit(String examId, String o) {
		List<DcSupExamQuotaOrgVo> assessmentUnit = dcSupExamScoreService.findAssessmentUnit(examId, o);
		DcSupExamScore dcSupExamScore = new DcSupExamScore();
		dcSupExamScore.setExamId(examId);
		dcSupExamScore.setScoreStatus("2");
		List<DcSupExamScore> gjdcSupExamScores = dcSupExamScoreService.findDcSupExamScoreList(dcSupExamScore);
		//查询单项评分提交
		dcSupExamScore.setScoreType("3");
		List<DcSupExamScore> dxdcSupExamScores = dcSupExamScoreService.findDxExamScoreList(dcSupExamScore);
		DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo = new DcSupExamSumQuotaInfo();
		dcSupExamSumQuotaInfo.setExamId(examId);
		List<DcSupExamSumQuotaInfo> dcSupExamSumQuotaInfos = dcSupExamSumQuotaInfoService.findReleaseDcSUpExamSumQuotaInfo(dcSupExamSumQuotaInfo);

		for (DcSupExamQuotaOrgVo dcSupExamQuotaOrgVo : assessmentUnit) {
			List<DcSupExamScore> dcSupExamScoreListWithExameOrg = gjdcSupExamScores.stream().filter(x -> x.getExameOrg() != null).filter(x -> x.getExameOrg().equals(dcSupExamQuotaOrgVo.getExameOrg())).collect(Collectors.toList());
			List<DcSupExamScore> dxdcSupExamScoreListWithExameOrg = dxdcSupExamScores.stream().filter(x -> x.getExameOrg() != null).filter(x -> x.getExameOrg().equals(dcSupExamQuotaOrgVo.getExameOrg())).collect(Collectors.toList());
			DcSupExamQuota dcSupExamQuota = new DcSupExamQuota();
			dcSupExamQuota.setExamId(dcSupExamQuotaOrgVo.getExamId());
			dcSupExamQuota.setCreateOrg(dcSupExamQuotaOrgVo.getExameOrg());
			//报送数据
			List<DcSupExamSumQuotaInfo> collect = dcSupExamSumQuotaInfos.stream().filter(x -> x.getExameOrg().equals(dcSupExamQuotaOrgVo.getExameOrg())).collect(Collectors.toList());

			//关键指标数量
			long gjcount = collect.stream().filter(x->"1".equals(x.getQuotaGroup())).count();
			//单项指标数量
			long dxcount = collect.stream().filter(x->"2".equals(x.getQuotaGroup())).count();
			//提交分数数据
			long gjScoreCount = dcSupExamScoreListWithExameOrg.stream().filter(x -> "2".equals(x.getScoreType())).count();
			long dxScoreCount = dxdcSupExamScoreListWithExameOrg.stream().count();
			long sumScoreCount = dcSupExamScoreListWithExameOrg.stream().filter(x -> "9".equals(x.getScoreType())).count();

			//是否需要关键评分
			if (gjcount!=0){
				//未提交进入判断
				if (gjScoreCount==0){dcSupExamQuotaOrgVo.setSumScoreStatus("2");continue;}
			}

			//是提交单项指标
			if (dxcount!=0){
				//未提交进入判断
				if (dxScoreCount!=dxcount){dcSupExamQuotaOrgVo.setSumScoreStatus("3");continue;}
			}

			//判断汇总是否提交
			if (sumScoreCount==0){
				//未提交
				dcSupExamQuotaOrgVo.setSumScoreStatus("9");
			}else{
				//已提交
				dcSupExamQuotaOrgVo.setSumScoreStatus("0");
			}

		}
		return assessmentUnit;
	}

	public DcSupExamScore findDxExamScoreLimitOne(String examId,String exameOrg){
		DcSupExamScore dxScore = super.dao.findDxExamScoreLimitOne(examId,exameOrg);
		return dxScore;
	}

	public List<DcSupExamSumQuotaInfo> findDcSupExamSumScore(String examId, String exameOrg) {
		return super.dao.findDcSupExamSumScore(examId, exameOrg);
	}

	public List<DcSupExamQuotaAdd> findDcSupExamQuoatAdd(String examId, String exameOrg) {
		return super.dao.findDcSupExamQuoatAdd(examId, exameOrg);
	}


	/**
	 * 评分汇总 数据处理
	 *
	 * @param dcSupExamVo
	 */
	@Transactional
	public void saveSumScore(DcSupExamVo dcSupExamVo) {
		String userCode = UserUtils.getUser().getUserCode();
		String userName = UserUtils.getUser().getUserName();
		//打分单位
		Office currentOffice = sysOfficeUnitService.getLatestUnitByOffice();
		String examId = dcSupExamVo.getDcSupExamScore().getExamId();
		String exameOrg = dcSupExamVo.getExameOrg();
		//被考核单位
		Office office = EmpUtils.getOffice(exameOrg);

		// 判断汇总是否提交过
		DcSupExamScore dcSupExamScoreVo = new DcSupExamScore();
		dcSupExamScoreVo.setExamId(examId);
		dcSupExamScoreVo.setScoreType("9");
		dcSupExamScoreVo.setExameOrg(exameOrg);
		DcSupExamScore dcSupExamScore = dcSupExamScoreDao.findDcSupExamScore(dcSupExamScoreVo);
		if (dcSupExamScore != null) {
			throw new ServiceException("当前汇总已提交过了！");
		}
		dcSupExamScore = createNewDcSupExamScore(examId, null, "9", null, null, "2");
		dcSupExamScore.setScoreOrg(currentOffice.getOfficeCode());
		dcSupExamScore.setScoreOrgName(currentOffice.getOfficeName());
		dcSupExamScore.setExameOrg(office.getOfficeCode());
		dcSupExamScore.setExameOrgName(office.getOfficeName());

		//新增指标添加
		List<DcSupExamSumQuotaInfo> dcSupScoreList = dcSupExamVo.getDcSupScoreList();
		for (DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo : dcSupScoreList) {
			checkScore(dcSupExamSumQuotaInfo.getQuotaWeight(),dcSupExamSumQuotaInfo.getQuotaScore(),dcSupExamSumQuotaInfo.getPercentage());
		}
		List<DcSupExamQuotaAdd> dcSupExamQuotaAddList = dcSupExamVo.getDcSupExamQuotaAddList();
		List<DcSupExamSumScore> dcSupExamSumScores = new ArrayList<>();
		DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo = dcSupScoreList.stream().findFirst().orElseGet(DcSupExamSumQuotaInfo::new);
		for (DcSupExamQuotaAdd insertDcSupExamQuotaAdd : dcSupExamQuotaAddList) {
			insertDcSupExamQuotaAdd.setId(IdGen.nextId());
			insertDcSupExamQuotaAdd.setCreateDate(new Date());
			insertDcSupExamQuotaAdd.setCreateBy(userCode);
			insertDcSupExamQuotaAdd.setCreateByName(userName);
			insertDcSupExamQuotaAdd.setLastYearComplete(dcSupExamSumQuotaInfo.getLastYearComplete());
			insertDcSupExamQuotaAdd.setLastYaerGoal(dcSupExamSumQuotaInfo.getLastYaerGoal());
			insertDcSupExamQuotaAdd.setCurrentYaerGoal(dcSupExamSumQuotaInfo.getCurrentYaerGoal());
			insertDcSupExamQuotaAdd.setExameName(office.getOfficeName());
			insertDcSupExamQuotaAdd.setExameOrg(office.getOfficeCode());
			//校验分数
			if ("3".equals(insertDcSupExamQuotaAdd.getQuotaClass())){
				checkScore(insertDcSupExamQuotaAdd.getQuotaWeight(),(insertDcSupExamQuotaAdd.getQuotaWeight()-insertDcSupExamQuotaAdd.getQuotaScore()),insertDcSupExamQuotaAdd.getPercentage());
			}else {
				checkScore(insertDcSupExamQuotaAdd.getQuotaWeight(),insertDcSupExamQuotaAdd.getQuotaScore(),insertDcSupExamQuotaAdd.getPercentage());
			}

			//新新指标汇总数据
			DcSupExamSumScore newDcSupExamSumScore = dcSupExamScoreService.createNewDcSupExamSumScore(insertDcSupExamQuotaAdd, examId, office,currentOffice);
			dcSupExamSumScores.add(newDcSupExamSumScore);
		}
		//更新指标分数
		super.dao.updateDcSupExamSumScores(dcSupScoreList);
		//插入分数主表
		dcSupExamScoreDao.insertDcSupExamScore(dcSupExamScore);
		//插入加减分指标
		if (dcSupExamQuotaAddList.size()>0){
			dcSupExamQuotaAddDao.insertBatch(dcSupExamQuotaAddList);
			super.dao.insertBatch(dcSupExamSumScores);
		}
		//汇总表状态改变
		super.dao.updateDcSUpExamSumScoreStatus(examId, exameOrg);
		//处理计算总分数据
		dcSupExamOrgScoreService.SumDcSupExamOrgScore(examId, exameOrg);
		//处理评分汇总置为已办
		dcSupBacklogService.doBacklog(examId,"exam_sum_score");

	}

	public static void checkScore(Double quotaWeight,Double quotaScore,Double percentage){
		if (quotaWeight==null||quotaScore==null||percentage==null||percentage>120){throw new ServiceException("数据异常，评分失败！");}
//		BigDecimal b1 = new BigDecimal(quotaWeight.toString());
//		BigDecimal b2 = new BigDecimal(percentage.toString());
//		BigDecimal baseQuotaScore = new BigDecimal(quotaScore.toString());
//		BigDecimal percentageBd = b2.movePointLeft(2);
//		//保留三位小数 并且四舍五入
//		BigDecimal quotaScoreBd = percentageBd.multiply(b1).setScale(3, BigDecimal.ROUND_HALF_UP);
	//	if (quotaScore>quotaWeight*1.2){throw new ServiceException("数据异常，评分失败！");}
	}


	/**
	 * 创建评分主表对象
	 *
	 * @param examId
	 * @param noticeId
	 * @param scoreType
	 * @param contactName
	 * @param contactPhone
	 * @return
	 */
	public DcSupExamScore createNewDcSupExamScore(String examId, String noticeId, String scoreType, String contactName, String contactPhone, String scoreStatus) {
		DcSupExamScore dcSupExamScore = new DcSupExamScore();
		dcSupExamScore.setId(IdGen.nextId());
		dcSupExamScore.setExamId(examId);
		dcSupExamScore.setNoticeId(noticeId);
		dcSupExamScore.setScoreType(scoreType);
		dcSupExamScore.setContactName(contactName);
		dcSupExamScore.setContactPhone(contactPhone);
		dcSupExamScore.setCreateBy(UserUtils.getUser().getUserCode());
		dcSupExamScore.setCreateByName(UserUtils.getUser().getUserName());
		dcSupExamScore.setCreateDate(new Date());
		dcSupExamScore.setScoreStatus(scoreStatus);//确认分数
		return dcSupExamScore;
	}

	public List<DcSupExamQuotaAdd> findDcSUpExamMinuspointsQuotaInfo(String examId, String exameOrg) {
		return super.dao.findDcSUpExamMinuspointsQuotaInfo(examId,exameOrg);
	}

	public Page<DcSupExamInfo> findExamSumProgressList(DcSupExamInfo dcSupExamInfo) {
		List<DcSupExamInfo> list = dcSupExamInfoService.findPage(dcSupExamInfo).getList();
		for (DcSupExamInfo supExamInfo : list) {
			DcSupExamScore dcSupExamScore = new DcSupExamScore();
			dcSupExamScore.setExamId(supExamInfo.getId());
			dcSupExamScore.setScoreType("9");
			List<DcSupExamQuotaOrgVo> assessmentUnit = dcSupExamScoreService.findAssessmentUnit(supExamInfo.getId(), null);
			List<DcSupExamScore> dcSupExamScoreList = dcSupExamScoreService.findDcSupExamScoreList(dcSupExamScore);
			//判断当前任务汇总情况！
			List<String> exameOrgs = assessmentUnit.stream().map(DcSupExamQuotaOrgVo::getExameOrg).distinct().collect(Collectors.toList());
			List<String> subExameOrgs = dcSupExamScoreList.stream().map(DcSupExamScore::getExameOrg).distinct().collect(Collectors.toList());
			dcSupExamInfo.setExamSumScoreStatus("1");
			if (subExameOrgs.isEmpty()){
				//待汇总
				supExamInfo.setExamSumScoreStatus("1");
				continue;
			}

			if (exameOrgs.size()==subExameOrgs.size()&&subExameOrgs.containsAll(exameOrgs)){
				//完成汇总
				supExamInfo.setExamSumScoreStatus("3");
				continue;
			}

			if (subExameOrgs.size()>0){
				//汇总中
				supExamInfo.setExamSumScoreStatus("2");
				continue;
			}

		}
		return dcSupExamInfo.getPage().setList(list);
	}
	@Transactional(readOnly=false)
	public int withdrawSumScore(String examId, String exameOrg) {
		//查出加分项和倒扣分项id集合 ，score_source=2,dc_sup_exam_sum_score,dc_sup_exam_quota_add,quota_id=quota_add.id
		List<String> ids = dao.findSumscoreAndQuotaAdd(examId,exameOrg);
		if(ids!=null && ids.size()>0){
			//删除评分汇总里score_source=2 加分倒扣分数据,删除add表数据
			int delSum = dao.deleteSumScoreByIds(ids);
			int delAdd = dao.deleteQuotaAddByIds(ids);
			if(delSum==0 || delAdd==0){
				throw new ServiceException("删除倒扣分数据失败,联系管理员");
			}
		}
		//更新评分汇总数据已提交为未提交
		int sumStatus = dao.updateDcSUpExamSumScoreStatusOne(examId,exameOrg);
		//删除评分主表score_type=9数据
		int delScore = dao.deleteQuotaScore(examId,exameOrg);
		if(sumStatus>0 && delScore>0){
			return 1;
		}
		return 0;
	}
}